package com.gzc.just.play.last.war.common.message.handler;

import com.gzc.just.play.last.war.common.battle.BattleManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Player attack message handler
 */
@Component
public class PlayerAttackHandler implements MessageHandlerInterface {

    private static final Logger log = LoggerFactory.getLogger(PlayerAttackHandler.class);

    private final BattleManager battleManager;
    private final ObjectMapper objectMapper;
    
    public PlayerAttackHandler(BattleManager battleManager, ObjectMapper objectMapper) {
        this.battleManager = battleManager;
        this.objectMapper = objectMapper;
    }

    @Override
    public void handle(Long playerId, Object messageData) {
        try {
            // Parse attack data
            Map<String, Object> attackData = objectMapper.convertValue(messageData, Map.class);
            
            Long targetId = Long.valueOf(attackData.get("targetId").toString());
            String attackType = (String) attackData.getOrDefault("attackType", "normal");
            
            // Handle attack in battle
            if (battleManager.isPlayerInBattle(playerId)) {
                battleManager.processPlayerAttack(playerId, targetId, attackType);
            } else {
                log.warn("Player {} is not in a battle but sent attack message", playerId);
            }
            
            log.debug("Player {} attacked target {} with type: {}", playerId, targetId, attackType);
        } catch (Exception e) {
            log.error("Error processing player attack for player: {}", playerId, e);
        }
    }
}